import {
  observable,
  action,
  makeObservable,
  computed,
  makeAutoObservable,
} from "mobx";

//默认情况下任何方法都可以更改可观察的状态，可以通过配置约束状态只能通过 Action 函数更改
// configure({ enforceActions: "observed" });
class AppleBasketStore {
  genAppleCount = 1;
  apples = [
    {
      id: 0,
      weight: 233,
      eaten: false,
    },
  ];
  isPicking = false;
  buttonText = "摘苹果";
  get appleStatus() {
    let status = {
      appleNow: {
        quantity: 0,
        weight: 0,
      },
      appleEaten: {
        quantity: 0,
        weight: 0,
      },
    };
    this.apples.forEach((apple) => {
      let selector = apple.isEaten ? "appleEaten" : "appleNow";
      status[selector].quantity++;
      status[selector].weight += apple.weight;
    });
    return status;
  }

  constructor() {
    // makeAutoObservable(this);

    makeObservable(this, {
      isPicking: observable,
      buttonText: observable,
      apples: observable,
      appleStatus: computed,
      genApple: action.bound,
      eatApple: action.bound, // 绑定this
    });
  }

  genApple() {
    console.log("[genapple]", this);
    this.isPicking = true;
    this.buttonText = "采摘中";

    setTimeout(() => {
      const appleWeight = Math.floor(200 + Math.random() * 50);
      console.log("[genApple]", appleWeight);
      this.apples.push({
        id: this.genAppleCount++,
        weight: appleWeight,
        eaten: false,
      });
      // this.genAppleCount += 1;
      this.isPicking = false;
      this.buttonText = "摘苹果";
    }, 1000);
  }

  eatApple(appleId) {
    console.log("index", appleId);
    let targetIndex = "";
    this.apples.forEach((apple, index) => {
      if (apple.id === appleId) {
        targetIndex = index;
      }
    });
    this.apples[targetIndex].isEaten = true;
  }
}

export default AppleBasketStore;
